/*global define, require */

define(function(require, exports, module) {

    'use strict';

    var angular = require('angular'),
        services = require('services/services'),
        config = require('config'),
        controllers = angular.module('app.controllers', ['app.services', 'app.config']);

    controllers.controller('IndexCtrl', require('controllers/IndexCtrl'));
    controllers.controller('LoginCtrl', require('controllers/LoginCtrl'));

    controllers.controller('product_ItemCtrl', require('controllers/product/ItemCtrl'));
    controllers.controller('product_DetailCtrl', require('controllers/product/DetailCtrl'));
    controllers.controller('product_ItemOtcCtrl', require('controllers/product/ItemOtcCtrl'));
    controllers.controller('product_ItemOtcFloatCtrl', require('controllers/product/ItemOtcFloatCtrl'));
    controllers.controller('product_DetailOtcCtrl', require('controllers/product/DetailOtcCtrl'));
    controllers.controller('product_ItemQDIICtrl', require('controllers/product/ItemQDIICtrl'));
    //controllers.controller('product_IndexCtrl', require('controllers/product/IndexCtrl'));
    controllers.controller('product_CurrentTermCtrl', require('controllers/product/CurrentTermCtrl'));
    controllers.controller('product_MoreCtrl', require('controllers/product/MoreCtrl'));
    controllers.controller('product_StarTermCtrl', require('controllers/product/StarTermCtrl'));
    controllers.controller('product_ShortTermCtrl', require('controllers/product/ShortTermCtrl'));
    controllers.controller('product_TFTermCtrl', require('controllers/product/TFTermCtrl'));
    controllers.controller('product_LongTermCtrl', require('controllers/product/LongTermCtrl'));
    controllers.controller('product_GoldTermCtrl', require('controllers/product/GoldTermCtrl'));
    controllers.controller('product_QDIITermCtrl', require('controllers/product/QDIITermCtrl'));
    controllers.controller('product_IndexTermCtrl', require('controllers/product/IndexTermCtrl'));
    controllers.controller('product_StockTermCtrl', require('controllers/product/StockTermCtrl'));
    controllers.controller('product_SearchCtrl', require('controllers/product/SearchCtrl'));
    controllers.controller('product_FundTermCtrl', require('controllers/product/FundTermCtrl'));
    controllers.controller('product_RateCtrl', require('controllers/product/RateCtrl'));


    controllers.controller('help_IndexCtrl', require('controllers/help/IndexCtrl'));
    controllers.controller('help_ItemCtrl', require('controllers/help/ItemCtrl'));
    controllers.controller('help_ListCtrl', require('controllers/help/ListCtrl'));

    controllers.controller('open_PrepareCtrl', require('controllers/open/PrepareCtrl'));
    controllers.controller('open_MsgVerifyCtrl', require('controllers/open/MsgVerifyCtrl'));
    controllers.controller('open_SelectBranchCtrl', require('controllers/open/SelectBranchCtrl'));
    controllers.controller('open_UploadIDCtrl', require('controllers/open/UploadIDCtrl'));
    controllers.controller('open_PersonInfoCtrl', require('controllers/open/PersonInfoCtrl'));
    controllers.controller('open_InstallCertCtrl', require('controllers/open/InstallCertCtrl'));
    controllers.controller('open_RiskAssessCtrl', require('controllers/open/RiskAssessCtrl'));
    controllers.controller('open_SetPwdCtrl', require('controllers/open/SetPwdCtrl'));
    controllers.controller('open_SignAgreementCtrl', require('controllers/open/SignAgreementCtrl'));
    controllers.controller('open_RevisitPaperCtrl', require('controllers/open/RevisitPaperCtrl'));
    controllers.controller('open_OpenResultCtrl', require('controllers/open/OpenResultCtrl'));
    controllers.controller('open_ChannelRiskCtrl', require('controllers/open/ChannelRiskCtrl'));
    controllers.controller('open_BindDepositBankCtrl', require('controllers/open/BindDepositBankCtrl'));
    controllers.controller('open_BindQuickBankCtrl', require('controllers/open/BindQuickBankCtrl'));
    controllers.controller('open_FillCustomerInfoCtrl', require('controllers/open/FillCustomerInfoCtrl'));

    controllers.controller('account_ConcernCtrl', require('controllers/account/ConcernCtrl'));
    controllers.controller('account_IndexCtrl', require('controllers/account/IndexCtrl'));
    controllers.controller('account_AssetsIndexCtrl', require('controllers/account/AssetsIndexCtrl'));
    controllers.controller('account_ManagerCtrl', require('controllers/account/ManagerCtrl'));
    controllers.controller('account_OpenTACtrl', require('controllers/account/OpenTACtrl'));
    controllers.controller('account_OpenAccountCtrl', require('controllers/account/OpenAccountCtrl'));
    controllers.controller('account_OpenAccountIdCtrl', require('controllers/account/OpenAccountIdCtrl'));
    controllers.controller('account_OpenAccountVideoCtrl', require('controllers/account/OpenAccountVideoCtrl'));
    controllers.controller('account_TransAccountCtrl', require('controllers/account/TransAccountCtrl'));
    controllers.controller('account_AgreementListCtrl', require('controllers/account/AgreementListCtrl'));
    controllers.controller('account_AgreementCtrl', require('controllers/account/AgreementCtrl'));
    //controllers.controller('account_EasyFinancingCtrl', require('controllers/account/EasyFinancingCtrl'));
    //controllers.controller('account_EasyFinancingOpenCtrl', require('controllers/account/EasyFinancingOpenCtrl'));
    //controllers.controller('account_EasyFinancingCreditCtrl', require('controllers/account/EasyFinancingCreditCtrl'));
    //controllers.controller('account_EasyFinancingAgreementCtrl', require('controllers/account/EasyFinancingAgreementCtrl'));
    //controllers.controller('account_EasyFinancingJurisdictionCtrl', require('controllers/account/EasyFinancingJurisdictionCtrl'));
    //controllers.controller('account_EasyFinancingIntelligenceLoanCtrl', require('controllers/account/EasyFinancingIntelligenceLoanCtrl'));
    //controllers.controller('account_EasyFinancingManualLoanCtrl', require('controllers/account/EasyFinancingManualLoanCtrl'));
    //controllers.controller('account_EasyFinancingManualCtrl', require('controllers/account/EasyFinancingManualCtrl'));
    //controllers.controller('account_EasyFinancingLoanCtrl', require('controllers/account/EasyFinancingLoanCtrl'));
    //controllers.controller('account_EasyFinancingHomeCtrl', require('controllers/account/EasyFinancingHomeCtrl'));
    //controllers.controller('account_EasyFinancingRepaymentCtrl', require('controllers/account/EasyFinancingRepaymentCtrl'));
    //controllers.controller('account_EasyFinancingPledgeCtrl', require('controllers/account/EasyFinancingPledgeCtrl'));
    //controllers.controller('account_EasyFinancingSharesDetailCtrl', require('controllers/account/EasyFinancingSharesDetailCtrl'));
    //controllers.controller('account_EasyFinancingRepayCtrl', require('controllers/account/EasyFinancingRepayCtrl'));
    //controllers.controller('account_EasyFinancingCounterCtrl', require('controllers/account/EasyFinancingCounterCtrl'));
    //controllers.controller('account_BorrowingPeriodCtrl', require('controllers/account/BorrowingPeriodCtrl'));
    //controllers.controller('account_UsageOfLoanCtrl', require('controllers/account/UsageOfLoanCtrl'));
    //controllers.controller('account_EsignatureCtrl', require('controllers/account/EsignatureCtrl'));
    controllers.controller('account_EntrepreneurshipCtrl', require('controllers/account/EntrepreneurshipCtrl'));
    controllers.controller('account_SaleDepartmentCtrl', require('controllers/account/SaleDepartmentCtrl'));
    controllers.controller('account_SignCtrl', require('controllers/account/SignCtrl'));
    controllers.controller('account_RelationshipCtrl', require('controllers/account/RelationshipCtrl'));
    controllers.controller('account_DegreeCtrl', require('controllers/account/DegreeCtrl'));
    controllers.controller('account_ProfessionCtrl', require('controllers/account/ProfessionCtrl'));
    controllers.controller('account_PhoneModifyCtrl', require('controllers/account/PhoneModifyCtrl'));
    controllers.controller('account_ModifyPhoneFirstCtrl', require('controllers/account/ModifyPhoneFirstCtrl'));
    controllers.controller('account_ModifyPhoneLastCtrl', require('controllers/account/ModifyPhoneLastCtrl'));
    controllers.controller('account_ResetPhoneFirstCtrl', require('controllers/account/ResetPhoneFirstCtrl'));
    controllers.controller('account_ResetPhoneSecondCtrl', require('controllers/account/ResetPhoneSecondCtrl'));
    controllers.controller('account_ResetPhoneThirdCtrl', require('controllers/account/ResetPhoneThirdCtrl'));
    controllers.controller('account_PostCodeCtrl', require('controllers/account/PostCodeCtrl'));
    controllers.controller('account_AddressCtrl', require('controllers/account/AddressCtrl'));
    //controllers.controller('account_MessageCtrl', require('controllers/account/MessageCtrl'));
    //controllers.controller('account_DetailCtrl', require('controllers/account/DetailCtrl'));
    controllers.controller('account_IdentificationCtrl', require('controllers/account/IdentificationCtrl'));
    controllers.controller('account_ChangeIdCtrl', require('controllers/account/ChangeIdCtrl'));
    controllers.controller('account_IdCheckCtrl', require('controllers/account/IdCheckCtrl'));
    controllers.controller('account_UserInfoVideoCtrl', require('controllers/account/UserInfoVideoCtrl'));
    controllers.controller('account_ModifyPwdCtrl', require('controllers/account/ModifyPwdCtrl'));
    controllers.controller('account_RiskCtrl', require('controllers/account/RiskCtrl'));
    controllers.controller('account_RiskEvalCtrl', require('controllers/account/RiskEvalCtrl'));
    controllers.controller('account_BankCtrl', require('controllers/account/BankCtrl'));
    controllers.controller('account_UnbindBankCtrl', require('controllers/account/UnbindBankCtrl'));
    controllers.controller('account_SharesCtrl', require('controllers/account/SharesCtrl'));
    controllers.controller('account_OrdersCtrl', require('controllers/account/OrdersCtrl'));
    controllers.controller('account_OrderProdHistoryCtrl', require('controllers/account/OrderProdHistoryCtrl'));
    controllers.controller('account_ShareDetailCtrl', require('controllers/account/ShareDetailCtrl'));
    controllers.controller('account_ShareDetailShortCtrl', require('controllers/account/ShareDetailShortCtrl'));
    controllers.controller('account_ShareDetailBankCtrl', require('controllers/account/ShareDetailBankCtrl'));
    controllers.controller('account_ShareDetailGatherCtrl', require('controllers/account/ShareDetailGatherCtrl'));
    controllers.controller('account_ShareDetailQDIICtrl', require('controllers/account/ShareDetailQDIICtrl'));
    controllers.controller('account_OrderDetailCtrl', require('controllers/account/OrderDetailCtrl'));
    controllers.controller('account_RechargeCtrl', require('controllers/account/RechargeCtrl'));
    controllers.controller('account_QueryBalanceCtrl', require('controllers/account/QueryBalanceCtrl'));
    controllers.controller('account_WithdrawCtrl', require('controllers/account/WithdrawCtrl'));
    controllers.controller('account_TransferDetailsCtrl', require('controllers/account/TransferDetailsCtrl'));
    controllers.controller('account_RechargeAndWithdrawCtrl', require('controllers/account/RechargeAndWithdrawCtrl'));
    controllers.controller('account_OpenStocksHKCtrl', require('controllers/account/OpenStocksHKCtrl'));
    controllers.controller('account_OpenKnowledgeCtrl', require('controllers/account/OpenKnowledgeCtrl'));
    controllers.controller('account_OpenEvaluationCtrl', require('controllers/account/OpenEvaluationCtrl'));
    controllers.controller('account_OpenRiskCtrl', require('controllers/account/OpenRiskCtrl'));
    controllers.controller('account_OpenAgreementCtrl', require('controllers/account/OpenAgreementCtrl'));

    controllers.controller('trade_BuyCtrl', require('controllers/trade/BuyCtrl'));
    controllers.controller('trade_AgreementListCtrl', require('controllers/trade/AgreementListCtrl'));
    controllers.controller('trade_AgreementCtrl', require('controllers/trade/AgreementCtrl'));
    controllers.controller('trade_AutographCtrl', require('controllers/trade/AutographCtrl'));
    controllers.controller('trade_SelectPayWayCtrl', require('controllers/trade/SelectPayWayCtrl'));
    controllers.controller('trade_SellCtrl', require('controllers/trade/SellCtrl'));

    controllers.controller('promo_UeRewardCtrl', require('controllers/promo/UeRewardCtrl'));
    controllers.controller('promo_SubjectCtrl', require('controllers/promo/SubjectCtrl'));
    controllers.controller('promo_PastSubjectCtrl', require('controllers/promo/PastSubjectCtrl'));
    controllers.controller('promo_OtcCtrl', require('controllers/promo/OtcCtrl'));
    controllers.controller('promo_WxQuestionCtrl', require('controllers/promo/WxQuestionCtrl'));
    controllers.controller('promo_ThemeCtrl', require('controllers/promo/ThemeCtrl'));
    controllers.controller('promo_TermThemeCtrl', require('controllers/promo/TermThemeCtrl'));
    controllers.controller('promo_BankThemeCtrl', require('controllers/promo/BankThemeCtrl'));
    controllers.controller('promo_RewardCtrl', require('controllers/promo/RewardCtrl'));
    controllers.controller('promo_PreviewCtrl', require('controllers/promo/PreviewCtrl'));

    controllers.controller('us_IndexCtrl', require('controllers/us/IndexCtrl'));
    controllers.controller('us_FeedbackCtrl', require('controllers/us/FeedbackCtrl'));

    //初始化
    controllers.run(['$rootScope', '$state', '$ionicHistory', 'LocalCacheService', 'BASE_PATH',
        '$http', 'offline', 'CacheFactory', '$cordovaNetwork', 'PULLING_TEXT', 'REFRESHING_TEXT', 'TdxLocalFuncService', 'ThsLocalFuncService','WebService','$location',
        function($rootScope, $state, $ionicHistory, LocalCacheService, BASE_PATH, $http, offline,
            CacheFactory, $cordovaNetwork, PULLING_TEXT, REFRESHING_TEXT, TdxLocalFuncService, ThsLocalFuncService,WebService,$location) {

            $http.defaults.cache = CacheFactory.createCache('offlineCache', {
                deleteOnExpire: 'none',
                maxAge: 0,
                storageMode: 'localStorage',
                storagePrefix: "tfzq."
            });

            offline.start($http);

            $rootScope.toolbarDisplay = true;
            $rootScope.basePath = BASE_PATH;
            $rootScope.PULLING_TEXT = PULLING_TEXT;
            $rootScope.REFRESHING_TEXT = REFRESHING_TEXT;
            $rootScope.isOffline = false;
            $rootScope.$on('$cordovaNetwork:online', function(event, networkState) {
                $rootScope.isOffline = false;
            });
            $rootScope.$on('$cordovaNetwork:offline', function(event, networkState) {
                console.log("got offline");
                $rootScope.isOffline = true;

            });

            $rootScope.closeDigitalKeyboard = function() { //关闭数字键盘
                if (typeof tf !== 'undefined' && typeof tf.digitalKeyboard !== 'undefined') {
                    tf.digitalKeyboard.close(function(status) {});
                }
            };

            $rootScope.goIndex = function() {
                if (typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event", { eventID: "s27" }, null, null);
                }
                $state.go("tab.index");
            };

            $rootScope.goIndex_2 = function() {
                if (typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event", { eventID: "s27" }, null, null);
                }
                $state.go("tab.index");
            };
            $rootScope.goIndex_3 = function() {
                if (typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event", { eventID: "s27" }, null, null);
                }
                $state.go("tab.index");
            };
            $rootScope.goIndex_4 = function() {
                if (typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event", { eventID: "s27" }, null, null);
                }
                $state.go("tab.index");
            };
            $rootScope.goIndex_5 = function() {
                if (typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event", { eventID: "s27" }, null, null);
                }
                $state.go("tab.index");
            };
            $rootScope.goIndex_6 = function() {
                if (typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event", { eventID: "s27" }, null, null);
                }
                $state.go("tab.index");
            };
            $rootScope.goIndex_7 = function() {
                if (typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event", { eventID: "s27" }, null, null);
                }
                $state.go("tab.index");
            };

            $rootScope.goProductIndex = function() {
                if (typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event", { eventID: "s28" }, null, null);
                }
                $state.go("tab.product-index");
            };


            $rootScope.goAccountIndex = function() {
                if (typeof Messenger != 'undefined') {
                    Messenger.sendMsg("ym_event", { eventID: "s29" }, null, null);
                }
                //获取缓存的用户信息
                var user = LocalCacheService.getUser();
                if (!user) {
                    //取消默认跳转行为
                    //event.preventDefault();
                    //跳转到登陆界面
                    var currentView = $ionicHistory.currentView();
                    $state.go("login", {
                        from: currentView.stateName,
                        fromParams: angular.toJson(currentView.stateParams),
                        w: 'notLogin',
                        to: "tab.account-assets-index",
                        toParams: ""
                    });
                } else {
                    //取消默认跳转行为
                    //event.preventDefault();
                    $state.go("tab.account-assets-index");
                }

            };

            $rootScope.$on('$ionicView.beforeEnter', function() {
                // var stateName = $state.current.name;
                //$rootScope.hideTabs = false;
                //if (stateName === 'tab.index' || stateName === 'tab.product-index'
                //    || stateName === 'tab.account-index') {
                //    $rootScope.hideTabs = false;
                //} else {
                $rootScope.hideTabs = true;
                angular.element(document.querySelector('#appLoading')).remove();
                //}
            });

            //拦截
            $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
                if (typeof Messenger != 'undefined') {
                    if (fromState && fromState.name != "") {
                        Messenger.sendMsg("ym_endLogPageView", { pageID: fromState.url }, null, null);
                    }
                    Messenger.sendMsg("ym_beginLogPageView", { pageID: toState.url }, null, null);
                }
                if(fromState.name!='tab.index'){
                    WebService.wtAddAccessRecord("gcs_fin_page", fromState.url , $location.url(), null);
                }
                if (typeof tf !== 'undefined' && typeof tf.digitalKeyboard != 'undefined') {
                    tf.digitalKeyboard.close(function(status) {});
                }
                if (!toState.loginStatus && !toState.openStatus) { //未设置登录拦截、开户拦截的请求，直接跳转
                    return;
                }
                if (toState.loginStatus) { //登陆拦截
                    if (!LocalCacheService.getUser()) {
                        event.preventDefault();
                        if (TdxLocalFuncService.isTDX()) {
                            TdxLocalFuncService.checkUser(function() {
                                if(toState.name!='tab.account-index'){
                                    $state.go(toState, toParams);
                                }
                            });
                        } else if (ThsLocalFuncService.isTHS()) {
                            ThsLocalFuncService.checkUser(function() {
                                $state.go(toState, toParams);
                            }, function() {
                                //跳转到登陆界面
                                $state.go("login", {
                                    from: fromState.name,
                                    fromParams: angular.toJson(fromParams),
                                    w: 'notLogin',
                                    to: toState.name,
                                    toParams: angular.toJson(toParams)
                                });
                            });
                        } else {
                            //跳转到登陆界面
                            $state.go("login", {
                                from: fromState.name,
                                fromParams: angular.toJson(fromParams),
                                w: 'notLogin',
                                to: toState.name,
                                toParams: angular.toJson(toParams)
                            });
                        }
                    } else {
                        if (ThsLocalFuncService.isTHS()) {
                            ThsLocalFuncService.getActivePtUser().then(function(data) {
                                //ThsLocalFuncService.loginTap(data,function(){});
                            }, function() {
                                LocalCacheService.removeUser();
                                $state.go("login", {
                                    from: fromState.name,
                                    fromParams: angular.toJson(fromParams),
                                    w: 'notLogin',
                                    to: toState.name,
                                    toParams: angular.toJson(toParams)
                                });
                            })
                        }
                    }
                }

                if (toState.openStatus && !LocalCacheService.getOpenUser()) { //开户拦截
                    //取消默认跳转行为
                    event.preventDefault();
                    //跳转到手机验证页
                    $state.go("open-msgVerify");
                }
            });

            $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
                if (TdxLocalFuncService.isTDX()) {
                    if (toState.name == 'tab.index') {
                        TdxLocalFuncService.tdxShowBottomBar();
                        $rootScope.toolbarDisplay = true;
                    } else {
                        if ($rootScope.toolbarDisplay) {
                            TdxLocalFuncService.tdxHideBottomBar();
                            $rootScope.toolbarDisplay = false;
                        }
                    }
                    TdxLocalFuncService.tdxTradeLockRefresh();
                }
            });

            $rootScope.$on('userIntercepted', function(errorType, data) {
                if ($state.current.name != "login") {
                    if (TdxLocalFuncService.isTDX()) {
                        TdxLocalFuncService.checkUser(function() {
                            TdxLocalFuncService.tdxTradeLocked().then(function (data) {
                                if (data.text == '1' || data.text==1) {
                                    return;
                                } else {
                                    $state.go("tab.account-assets-index");
                                }
                            });
                        });
                    } else {
                        $state.go("login", { from: $state.current.name, w: data });
                    }
                }
            });

            $rootScope.$on('openUserIntercepted', function(errorType, data) {
                // 跳转到手机号验证界面
                $state.go("open-msgVerify");
            });

            var onReceiveMessage = function(event) {
                var message;
                if (device.platform == "Android") {
                    message = window.plugins.PushPlugin.receiveMessage.message;
                } else {
                    message = event.message;
                }
                if (typeof message != 'undefined') {
                    var bToObj = JSON.parse(message);
                    //var extras = window.plugins.PushPlugin.extras
                    var toView = bToObj.value.view;
                    if (typeof toView != 'undefined') {
                        var params = bToObj.value.params;
                        $state.go(toView, params);
                    }
                }
            };
            //APP在后台中，获取点击通知内容
            var onOpenNotification = function(event) {
                try {
                    var alertContent;
                    if (device.platform == "Android") {
                        alertContent = window.plugins.PushPlugin.openNotification.alert;
                    } else {
                        alertContent = event.aps.alert;
                    }
                    console.log("open Notificaiton:" + alertContent);
                    if (typeof alertContent != 'undefined') {
                        var bToObj = JSON.parse(alertContent.body);
                        //var extras = window.plugins.PushPlugin.extras
                        var toView = bToObj.value.view;
                        if (typeof toView != 'undefined') {
                            var params = bToObj.value.params;
                            $state.go(toView, params);
                        }
                    }
                } catch (exception) {
                    console.log("PushPlugin:onOpenNotification" + exception);
                }
            };
            //APP在运行状态中，获取通知内容
            var onReceiveNotification = function(event) {
                try {
                    var alertContent;
                    if (device.platform == "Android") {
                        alertContent = window.plugins.PushPlugin.receiveNotification.alert;
                    } else {
                        alertContent = event.aps.alert;
                    }
                    console.log("Receive Notificaiton:" + alertContent);
                    if (typeof alertContent != 'undefined') {
                        var bToObj = JSON.parse(alertContent.body);
                        //var extras = window.plugins.PushPlugin.extras
                        var toView = bToObj.value.view;
                        if (typeof toView != 'undefined') {
                            var params = bToObj.value.params;
                            $state.go(toView, params);
                        }
                    }

                } catch (exeption) {
                    console.log(exception)
                }
            };

            document.addEventListener("push.receiveMessage", onReceiveMessage, false);
            document.addEventListener("push.openNotification", onOpenNotification, false);
            document.addEventListener("push.receiveNotification", onReceiveNotification, false);
        }
    ]);

    return controllers;
});
